
package com.gps.gate.protocol;

import com.gps.common.helper.BitUtil;
import com.gps.common.helper.Checksum;
import com.gps.common.helper.DateBuilder;
import com.gps.common.helper.UnitsConverter;
import com.gps.common.model.Position;
import com.gps.gate.BaseProtocolDecoder;
import com.gps.gate.NetworkMessage;
import com.gps.gate.Protocol;
import com.gps.gate.database.ActiveDevice;
import com.gps.gate.helper.BcdUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class Jt808ProtocolDecoder extends BaseProtocolDecoder {

    public Jt808ProtocolDecoder(Protocol protocol) {
        super(protocol);
    }

    public static final int MSG_GENERAL_RESPONSE = 0x8001;
    public static final int MSG_TERMINAL_REGISTER = 0x0100;
    public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100;
    public static final int MSG_TERMINAL_AUTH = 0x0102;
    public static final int MSG_LOCATION_REPORT = 0x0200;
    public static final int MSG_LOCATION_BATCH = 0x0704;
    public static final int MSG_OIL_CONTROL = 0XA006;

    public static final int RESULT_SUCCESS = 0;

    public static ByteBuf formatMessage(int type, ByteBuf id, ByteBuf data) {
        ByteBuf buf = Unpooled.buffer();
        buf.writeByte(0x7e);
        buf.writeShort(type);
        buf.writeShort(data.readableBytes());
        buf.writeBytes(id);
        buf.writeShort(1); // index
        buf.writeBytes(data);
        data.release();
        buf.writeByte(Checksum.xor(buf.nioBuffer(1, buf.readableBytes() - 1)));
        buf.writeByte(0x7e);
        return buf;
    }

    private void sendGeneralResponse(
            Channel channel, SocketAddress remoteAddress, ByteBuf id, int type, int index) {
        if (channel != null) {
            ByteBuf response = Unpooled.buffer();
            response.writeShort(index);
            response.writeShort(type);
            response.writeByte(RESULT_SUCCESS);
            channel.writeAndFlush(new NetworkMessage(
                    formatMessage(MSG_GENERAL_RESPONSE, id, response), remoteAddress));
        }
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        ByteBuf buf = (ByteBuf) msg;
        String s = ByteBufUtil.hexDump(buf);
        log.info("recv: {}", s);

        buf.readUnsignedByte(); // start marker
        int type = buf.readUnsignedShort();
        buf.readUnsignedShort(); // body length
        ByteBuf id = buf.readSlice(6); // phone number
        int index = buf.readUnsignedShort();

        ActiveDevice deviceSession = getDeviceSession(channel, remoteAddress, ByteBufUtil.hexDump(id));
        if (deviceSession == null) {
            return null;
        }
        if (type == MSG_TERMINAL_REGISTER) {
            if (channel != null) {
                ByteBuf response = Unpooled.buffer();
                response.writeShort(index);
                response.writeByte(RESULT_SUCCESS);
                response.writeBytes("authentication".getBytes(StandardCharsets.US_ASCII));
                channel.writeAndFlush(new NetworkMessage(
                        formatMessage(MSG_TERMINAL_REGISTER_RESPONSE, id, response), remoteAddress));
            }
        } else if (type == MSG_TERMINAL_AUTH) {
            sendGeneralResponse(channel, remoteAddress, id, type, index);
        } else if (type == 0x02) {
            sendGeneralResponse(channel, remoteAddress, id, type, index);
        } else if (type == MSG_LOCATION_REPORT) {
            return decodeLocation(deviceSession, buf);
        } else if (type == MSG_LOCATION_BATCH) {
            return decodeLocationBatch(deviceSession, buf);
        }
        return null;
    }

    private Position decodeLocation(ActiveDevice deviceSession, ByteBuf buf) {
        Position position = new Position(getProtocolName());
        position.setImei(deviceSession.getImei());
        int flags = buf.readInt();
        position.setValid(BitUtil.check(flags, 1));
        int alarm = buf.readInt();
        double lat = buf.readUnsignedInt() * 0.000001;
        double lon = buf.readUnsignedInt() * 0.000001;
        if (BitUtil.check(flags, 2)) {
            position.setLatitude(-lat);
        } else {
            position.setLatitude(lat);
        }
        if (BitUtil.check(flags, 3)) {
            position.setLongitude(-lon);
        } else {
            position.setLongitude(lon);
        }

        position.setAltitude(buf.readShort());
        position.setSpeed(UnitsConverter.knotsFromKph((float) (buf.readUnsignedShort() * 0.1)));
        position.setCourse(buf.readUnsignedShort());

        DateBuilder dateBuilder = new DateBuilder()
                .setYear(BcdUtil.readInteger(buf, 2))
                .setMonth(BcdUtil.readInteger(buf, 2))
                .setDay(BcdUtil.readInteger(buf, 2))
                .setHour(BcdUtil.readInteger(buf, 2))
                .setMinute(BcdUtil.readInteger(buf, 2))
                .setSecond(BcdUtil.readInteger(buf, 2));
        position.setTime(dateBuilder.getDate());

        // additional information

        while (buf.readableBytes() > 2) {
            int subtype = buf.readUnsignedByte();
            int length = buf.readUnsignedByte();
            switch (subtype) {
                case 0x01:
                    position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100);
                    break;
                case 0x30:
                    position.set(Position.KEY_RSSI, buf.readUnsignedByte());
                    break;
                case 0x31:
                    position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
                    break;
                default:
                    buf.skipBytes(length);
                    break;
            }
        }
        return position;
    }

    private List<Position> decodeLocationBatch(ActiveDevice deviceSession, ByteBuf buf) {
        List<Position> positions = new LinkedList<>();
        int count = buf.readUnsignedShort();
        buf.readUnsignedByte(); // location type
        for (int i = 0; i < count; i++) {
            int endIndex = buf.readUnsignedShort() + buf.readerIndex();
            positions.add(decodeLocation(deviceSession, buf));
            buf.readerIndex(endIndex);
        }
        return positions;
    }

}
